import React, {useEffect, useState} from "react";
import {Animated, ScrollView, Keyboard, StyleProp, ViewStyle, ScrollViewProps} from "react-native";
import {useSafeAreaInsets} from "react-native-safe-area-context";

export type KeyboardScrollViewProps = {
    style?: StyleProp<ViewStyle>;
    scrollViewProps?: ScrollViewProps;
    children?: any;
};

const KeyboardScrollView = ({
                                style = {},
                                scrollViewProps = {},
                                children = null
                            }: KeyboardScrollViewProps, ref: any) => {
    const insets = useSafeAreaInsets();
    const [paddingBottom, setPaddingBottom] = useState(new Animated.Value(0));

    useEffect(() => {
        Keyboard.addListener("keyboardWillShow", (e) => {
            //console.log("keyboardWillShow", e);
            Animated.timing(paddingBottom, {
                toValue: e.endCoordinates.height - insets.top - insets.bottom,
                duration: e.duration,
                useNativeDriver: false,
            }).start();
        });
        Keyboard.addListener("keyboardWillHide", (e) => {
            paddingBottom.setValue(0);
            // Animated.timing(paddingBottom, {
            //     toValue: 0,
            //     duration: e.duration,
            //     useNativeDriver: false,
            // }).start();
        });
    }, []);

    return (
        <Animated.View ref={ref} style={[style, {paddingBottom}]}>
            <ScrollView {...scrollViewProps}>{children}</ScrollView>
        </Animated.View>
    );
};

export default React.forwardRef(KeyboardScrollView);
